# encoding=utf-8

import sys, os
if hasattr(sys, 'frozen'):
    os.environ['PATH'] = sys._MEIPASS + ";" + os.environ['PATH']

import PyQt5.QtWidgets as qw
import PyQt5.QtCore as qc
import ui_main
from PyQt5.QtCore import Qt, pyqtSignal
import sys
import numpy as np
import random
import json

import logging
from serial import Serial
import threading
from time import sleep
from serial.serialutil import *
import serial.tools.list_ports

import home
import home_admin
import ui_login


class loginWidget(qw.QWidget, ui_login.Ui_Form):
    signal_recv_data = pyqtSignal(str)
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # init gui
        # self.statusbar.showMessage("status:ok")
        self.btn_login.clicked.connect(self.login_cb)

        # 变量
        self.username_element_list = ('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
                         'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
                         '1','2','3','4','5','6','7','8','9','_','&','#','@','$','*','^')

    def check_username(self, username):
        for item in username:
            if item not in self.username_element_list:
                return False
        return True
        
    def login_cb(self):
        print("Hello ............")
        username = self.Edit_username.text()
        password = self.Edit_password.text()
        print("username is %s, pass is %s" % (username, password))

        # 判断用户输入类型
        if ( len(username) >16 or len(password) > 16):
            qw.QMessageBox.warning(self, "警告", "用户名长度不能大于16")
        elif(False == self.check_username(username)):
            qw.QMessageBox.warning(self, "警告", "请检查用户名输入格式！")
        else:
            if username == "admin" and password == "123456":
                print("#################### Admin login success")
                self.set_mode(1)
                w_home_admin.show()
                self.close()
            elif username == "brown" and password == "123456":
                self.set_mode(0)
                w_home.show()
                self.close()
            else:
                qw.QMessageBox.warning(self, " ")

    def set_mode(self, mode):
        # 1: 管理员模式， 0：普通用户模式
        settings = qc.QSettings("config.ini", qc.QSettings.IniFormat)
        settings.setValue("SETUP/MODE", mode)
        mode = settings.value("SETUP/MODE")
        print("mode is %s" % mode)

# 显示登录页面， 然后进入管理员或者普通用户页面
if __name__ == "__main__":
    app = qw.QApplication(sys.argv)
    w = loginWidget()
    w_home = home.myWindow()
    w_home_admin = home_admin.myWindow()
    w.show()

    sys.exit(app.exec_())
